package com.tsinghuabigdata.edu.ddmath.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.adapter.BeansCourseAdapter;
import com.tsinghuabigdata.edu.ddmath.adapter.AdverPageAdapter;
import com.tsinghuabigdata.edu.ddmath.bean.BensCourse;
import com.tsinghuabigdata.edu.ddmath.util.DataUtils;
import com.tsinghuabigdata.edu.ddmath.view.GridViewWithHeaderAndFooter;
import com.tsinghuabigdata.edu.ddmath.view.LoadingPager;
import com.tsinghuabigdata.edu.ddmath.view.SpinnerView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;



/**
 * 豆豆课程
 * Created by Administrator on 2016/12/14.
 */

public class BeansCourseFragment extends MyBaseFragment implements SpinnerView.HanddleSpinnerView, ViewPager.OnPageChangeListener {

    private static final String TAG = "sky";

    private List<BensCourse> mAllList = new ArrayList<BensCourse>();
    private List<BensCourse> mList    = new ArrayList<BensCourse>();
    private BeansCourseAdapter mAdapter;

    private ImageView     mIvContactService;
    private SpinnerView   mSvGrade;
    private SpinnerView   mSvTime;
    private SpinnerView   mSvKind;
    private GridViewWithHeaderAndFooter mGvBeansCourse;
    private LoadingPager  mLoadingPager;
    private ImageView    mIvTop;

    private List<String> mListGrade;
    private List<String> mListTime;
    private List<String> mListKind;
    private List<String> mListComTime;
    private int          indexGrade;
    private int          indexTime;
    private int          indexKind;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {

        }
    };
    public  AutoScrollTask   mAutoScrollTask;
    private ViewPager        mViewPager;
    private LinearLayout     mIndicatorContainer;
    private int[]            imageRes;
    private Context          mContext;
    private AdverPageAdapter mAdverPageAdapter;
    private boolean firstVisible = true;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_beans_course, container, false);
        initView(root);
        initViewPager();
        initData();
        return root;
    }

    private void initView(View root) {
        mContext = getActivity();
        mViewPager = (ViewPager) root.findViewById(R.id.viewPager);
        mIndicatorContainer = (LinearLayout) root.findViewById(R.id.indicator_container);

        mIvContactService = (ImageView) root.findViewById(R.id.iv_contact_service);
        mSvGrade = (SpinnerView) root.findViewById(R.id.sv_grade);
        mSvTime = (SpinnerView) root.findViewById(R.id.sv_time);
        mSvKind = (SpinnerView) root.findViewById(R.id.sv_kind);
        mGvBeansCourse = (GridViewWithHeaderAndFooter) root.findViewById(R.id.gv_beans_course);
        mLoadingPager = (LoadingPager) root.findViewById(R.id.loading_pager);
        mIvTop = (ImageView) root.findViewById(R.id.iv_top);
        mLoadingPager.setTargetView(mGvBeansCourse);
        mLoadingPager.setEmptyText("未找到满足条件的课程，请重新搜索");

        mListGrade = Arrays.asList(getResources().getStringArray(R.array.grade));
        mListTime = Arrays.asList(getResources().getStringArray(R.array.time));
        mListKind = Arrays.asList(getResources().getStringArray(R.array.kind));
        mListComTime = Arrays.asList(getResources().getStringArray(R.array.comtime));
        mSvGrade.setText(mListGrade.get(0));
        mSvTime.setText(mListTime.get(0));
        mSvKind.setText(mListKind.get(0));

        mSvGrade.setHanddleSpinnerView(this);
        mSvTime.setHanddleSpinnerView(this);
        mSvKind.setHanddleSpinnerView(this);
        mSvGrade.setData(mListGrade);
        mSvGrade.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSvGrade.setText(mListGrade.get(position));
                mSvGrade.dismiss();
                mSvGrade.setSelectedPosition(position);
                indexGrade = position;
                queryBeansCourse();
            }
        });
        mSvTime.setData(mListTime);
        mSvTime.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSvTime.setText(mListTime.get(position));
                mSvTime.dismiss();
                mSvTime.setSelectedPosition(position);
                indexTime = position;
                queryBeansCourse();
            }
        });
        mSvKind.setData(mListKind);
        mSvKind.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSvKind.setText(mListKind.get(position));
                mSvKind.dismiss();
                mSvKind.setSelectedPosition(position);
                indexKind = position;
                queryBeansCourse();
            }
        });

        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        View headerView = layoutInflater.inflate(R.layout.header_view_beans_course, null);
        View footerView = layoutInflater.inflate(R.layout.footer_view_beans_course, null);
        mGvBeansCourse.addHeaderView(headerView);
        mGvBeansCourse.addFooterView(footerView);

        mGvBeansCourse.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                Log.i(TAG, "firstVisibleItem = " + firstVisibleItem);
                if (firstVisibleItem >= 7 && firstVisible) {
                    firstVisible = false;
                    TranslateAnimation ta = new TranslateAnimation(0, 0, 0, 0,
                            Animation.RELATIVE_TO_SELF, 2,
                            Animation.RELATIVE_TO_SELF, 0);
                    ta.setDuration(300);
                    ta.setFillAfter(true);
                    mIvTop.startAnimation(ta);
                } else if (firstVisibleItem < 7 && !firstVisible) {
                    firstVisible = true;
                    TranslateAnimation ta = new TranslateAnimation(0, 0, 0, 0,
                            Animation.RELATIVE_TO_SELF, 0,
                            Animation.RELATIVE_TO_SELF, 2);
                    ta.setDuration(300);
                    ta.setFillAfter(true);
                    mIvTop.startAnimation(ta);
                }
            }
        });
        mIvTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mGvBeansCourse.setSelection(0);
            }
        });
    }

    private void queryBeansCourse() {
        mLoadingPager.showLoading();
        mList.clear();
        //        Log.i(TAG, "indexGrade=" + indexGrade + "indexTime=" + indexTime + "indexKind=" + indexKind);
        //        Log.i(TAG, "Grade=" + mListGrade.get(indexGrade) + " Time=" + mListTime.get(indexTime) + " Kind=" + mListKind.get(indexKind));
        for (int i = 0; i < mAllList.size(); i++) {
            BensCourse vo = mAllList.get(i);
            boolean equalsGrade = "全部年级".equals(mListGrade.get(indexGrade)) || mListGrade.get(indexGrade).equals(vo.getGrade());
            boolean equalsTime = "全部学期".equals(mListComTime.get(indexTime)) || mListComTime.get(indexTime).equals(vo.getTime());
            boolean equalsKind = "全部类别".equals(mListKind.get(indexKind)) || mListKind.get(indexKind).equals(vo.getKind());
            if (equalsGrade && equalsTime && equalsKind) {
                mList.add(vo);
            }
        }
        Log.i(TAG, "mList.size() = " + mList.size());
        if (mList.size() == 0) {
            mLoadingPager.showEmpty();
        } else {
            mAdapter.notifyDataSetChanged();
            mLoadingPager.showTarget();
        }
    }


    private void initData() {
        mAllList.addAll(DataUtils.getBeansCourse());
        mList.clear();
        mList.addAll(mAllList);
        mAdapter = new BeansCourseAdapter(getActivity(), mList);
        mGvBeansCourse.setAdapter(mAdapter);
        mLoadingPager.showTarget();
        Log.i(TAG, "mList.size() = " + mList.size());
    }


    @Override
    public void select() {
        mSvGrade.dismiss();
        mSvTime.dismiss();
        mSvKind.dismiss();
    }

    private void initViewPager() {
        imageRes = new int[]{R.drawable.img_ad1, R.drawable.img_ad2, R.drawable.img_ad3};
        // 设置ViewPager的Adapter信息
        mAdverPageAdapter = new AdverPageAdapter(mContext, imageRes);
        mViewPager.setAdapter(mAdverPageAdapter);
        // 移除mIndicatorContainer里面的所有的视图
        int index = Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % imageRes.length;
        Log.i(TAG, "index=" + index);
        mViewPager.setCurrentItem(index);
        for (int i = 0; i < imageRes.length; i++) {
            ImageView imageView = (ImageView) mIndicatorContainer.getChildAt(i);
            if (i == 0) {
                imageView.setActivated(true);
            } else {
                imageView.setActivated(false);
            }
        }

        // 自动轮播
        // startScroll();
        if (mAutoScrollTask == null) {
            mAutoScrollTask = new AutoScrollTask();
            //            mAutoScrollTask.start();
        }
        // 设置viewPager滚动的监听
        mViewPager.setOnPageChangeListener(this);
        // 按下去的时候停止轮播
        mViewPager.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Log.i(TAG, "==ACTION_DOWN==");
                        // 停止轮播
                        // stopScroll();
                        if (mAutoScrollTask != null) {
                            mAutoScrollTask.stop();
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:

                        break;
                    case MotionEvent.ACTION_UP:
                        // case MotionEvent.ACTION_CANCEL:
                        Log.i(TAG, "==ACTION_UP==");
                        // 开始轮播
                        // startScroll();
                        if (mAutoScrollTask != null) {
                            mAutoScrollTask.start();
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }

    public class AutoScrollTask implements Runnable {
        /**
         * 开始滚动
         */
        public void start() {
            // 得到一个主线程的handler
            mHandler.removeCallbacks(this);
            mHandler.postDelayed(this, 5000);
        }

        /**
         * 停止滚动
         */
        public void stop() {
            // 移除任务
            mHandler.removeCallbacks(this);
        }

        @Override
        public void run() {
            int currentItem = mViewPager.getCurrentItem();
            currentItem++;
            mViewPager.setCurrentItem(currentItem);
            // 递归
            start();
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < imageRes.length; i++) {
            ImageView imageView = (ImageView) mIndicatorContainer.getChildAt(i);
            if (i == position % imageRes.length) {
                imageView.setActivated(true);
            } else {
                imageView.setActivated(false);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume()");
        if (mAutoScrollTask != null) {
            mAutoScrollTask.start();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i(TAG, "onPause()");
        if (mAutoScrollTask != null) {
            mAutoScrollTask.stop();
        }
    }

}
